package com.newfiber.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newfiber.business.constant.BusinessConstants;
import com.newfiber.business.domain.PatrolUser;
import com.newfiber.business.domain.request.patrolUser.PatrolUserQueryRequest;
import com.newfiber.business.domain.request.patrolUser.PatrolUserSaveBriefRequest;
import com.newfiber.business.domain.request.patrolUser.PatrolUserSaveRequest;
import com.newfiber.business.domain.request.patrolUser.PatrolUserUpdateRequest;
import com.newfiber.business.enums.EPatrolUserRefType;
import com.newfiber.business.enums.EPatrolUserType;
import com.newfiber.business.mapper.PatrolUserMapper;
import com.newfiber.business.service.IPatrolUserService;
import com.newfiber.common.core.exception.ServiceException;
import com.newfiber.common.core.web.service.BaseServiceImpl;
import com.newfiber.common.security.utils.SecurityUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 巡查人员Service业务层处理
 *
 * @author X.K
 * @date 2023-02-17
 */
@Service
public class PatrolUserServiceImpl extends BaseServiceImpl<PatrolUserMapper, PatrolUser> implements IPatrolUserService {

    @Resource
    private PatrolUserMapper patrolUserMapper;

    @Override
    public boolean insert(PatrolUserSaveRequest request) {
        List<PatrolUser> patrolUserList = new ArrayList<>();

        // 添加用户，添加的时候有可能会删除一部分，添加一部分用户。实现逻辑是：添加之前先删除已有的用户，然后在插入最新的用户列表。
        PatrolUserQueryRequest patrolUserQueryRequest = new PatrolUserQueryRequest();
        patrolUserQueryRequest.setRefType(request.getRefType());
        patrolUserQueryRequest.setRefId(request.getRefId());
        patrolUserQueryRequest.setUserType(request.getUserType());
        List<PatrolUser> patrolUsers = patrolUserMapper.selectByCondition(patrolUserQueryRequest);
        List<Long> idList = new ArrayList<>();
        for (PatrolUser patrolUser : patrolUsers) {
            Long id = patrolUser.getId();
            idList.add(id);
        }
        if (CollectionUtils.isNotEmpty(idList)) {
            String ids = StringUtils.join(idList.toArray(), ",");
            delete(ids);
        }

        if (StringUtils.isBlank(request.getUserIds())) {
            return false;
        }

        for (String userId : request.getUserIds().split(BusinessConstants.COMMA)) {
            PatrolUser patrolUser = new PatrolUser();
            BeanUtils.copyProperties(request, patrolUser);
            patrolUser.setUserId(Long.parseLong(userId));
            patrolUserList.add(patrolUser);
        }
        return saveBatch(patrolUserList, patrolUserList.size());
    }

    @Override
    public boolean save(EPatrolUserRefType refType, Long refId, List<PatrolUserSaveBriefRequest> patrolUserSaveBriefRequestList) {
        if (CollectionUtils.isEmpty(patrolUserSaveBriefRequestList)) {
            return true;
        }

        List<PatrolUser> patrolUserList = new ArrayList<>();
        for (PatrolUserSaveBriefRequest saveRequest : patrolUserSaveBriefRequestList) {
            PatrolUser patrolUser = new PatrolUser();
            patrolUser.setRefType(refType.getCode());
            patrolUser.setRefId(refId);
            patrolUser.setUserType(saveRequest.getUserType());
            patrolUser.setUserId(saveRequest.getUserId());
            patrolUser.setCreateTime(new Date());
            patrolUser.setCreateBy(SecurityUtils.getUsername());
            patrolUserList.add(patrolUser);
        }

        return saveBatch(patrolUserList);
    }

    @Override
    public boolean save(EPatrolUserRefType refType, Long refId, EPatrolUserType userType, List<Long> userIdList) {
        if (CollectionUtils.isEmpty(userIdList)) {
            return true;
        }

        List<PatrolUser> patrolUserList = new ArrayList<>();
        for (Long userId : userIdList) {
            PatrolUser patrolUser = new PatrolUser();
            patrolUser.setRefType(refType.getCode());
            patrolUser.setRefId(refId);
            patrolUser.setUserType(userType.getCode());
            patrolUser.setUserId(userId);
            patrolUser.setCreateTime(new Date());
            patrolUser.setCreateBy(SecurityUtils.getUsername());
            patrolUserList.add(patrolUser);
        }

        return saveBatch(patrolUserList);
    }

    @Override
    public boolean update(PatrolUserUpdateRequest request) {
        PatrolUser patrolUser = new PatrolUser();
        BeanUtils.copyProperties(request, patrolUser);
        return updateById(patrolUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String ids) {
        return deleteLogic(ids);
    }

    @Override
    public long patrolUserDistinctCount() {
        QueryWrapper<PatrolUser> queryWrapper = new QueryWrapper<PatrolUser>().select("distinct user_id").
                eq("user_type", EPatrolUserType.Patrol.getCode());
        return count(queryWrapper);
    }

    @Override
    public long patrolUserDistinctCount(String patrolType) {
        return patrolUserMapper.patrolUserDistinctCount(patrolType);
    }

    @Override
    public PatrolUser selectDetail(Long id) {
        PatrolUser patrolUser = patrolUserMapper.selectById(id);
        if (null == patrolUser) {
            throw new ServiceException(String.format("%s ID=%s 的记录不存在", this.getClass().getSimpleName(), id));
        }
        return patrolUser;
    }

    @Override
    public List<PatrolUser> selectPage(PatrolUserQueryRequest request) {
        if (StringUtils.isNotBlank(request.getRefIds())) {
            request.getRefIdList().addAll(Arrays.asList(request.getRefIds().split(",")));
        }
        return patrolUserMapper.selectByCondition(request);
    }

    @Override
    public List<PatrolUser> selectList(PatrolUserQueryRequest request) {
        if(BusinessConstants.FALSE_STR.equals(request.getUsed())){
            return patrolUserMapper.queryUnusedUser(request);
        }
        return patrolUserMapper.selectByCondition(request);
    }

}
